<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="125px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位类型" prop="position">
        <el-select v-model="queryParams.position" placeholder="请选择岗位类型" clearable>
          <el-option
            v-for="dict in dict.type.c_position"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交付小组" prop="payGroupName">
        <el-input
          v-model="queryParams.payGroupName"
          placeholder="请输入交付小组名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程分类" prop="classTypeName">
        <el-input
          v-model="queryParams.classTypeName"
          placeholder="请输入课程分类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所学教段" prop="teachSection">
        <el-select v-model="queryParams.teachSection" filterable size="large">
          <el-option :key="0" label="小学" value="0" />
          <el-option :key="1" label="初中" value="1" />
          <el-option :key="2" label="高中" value="2" />
        </el-select>
        <!-- <el-input v-model="queryParams.teachSection" placeholder="请输入所学教段" clearable
          @keyup.enter.native="handleQuery" /> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          :type="tableType === '0' ? 'primary' : 'default'"
          :plain="tableType !== '0'"
          icon="el-icon-user"
          size="mini"
          @click="refTable('0')"
          >教练</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="default"
          plain
          icon="el-icon-user"
          size="mini"
          @click="refTable('1')"
          >交付小组组长</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="default"
          plain
          icon="el-icon-user"
          size="mini"
          @click="refTable('2')"
          >学管师</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:Coach:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['course:Coach:remove']">删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 教练列表 -->
    <el-table
      v-loading="loading"
      :data="CoachList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="教练姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="phone" width="100px" />
      <el-table-column label="企微账号" align="center" prop="wxUserId" width="100px" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        v-if="tableType == '0' || tableType == '1'"
        label="性格特点"
        align="center"
        prop="personality"
        width="100px"
      />
      <el-table-column
        v-if="tableType == '0' || tableType == '1'"
        label="交付中心名称"
        align="center"
        prop="paCenterName"
      />
      <el-table-column
        v-if="tableType == '0' || tableType == '1'"
        label="交付中心编号"
        align="center"
        prop="paCenterCode"
        width="120px"
      />
      <el-table-column
        v-if="tableType == '0'"
        label="角色类型"
        align="center"
        prop="roleType"
        width="130px"
      >
        <template slot-scope="scope">
          <span>
            {{
              scope.row.roleType === "0"
                ? "教练"
                : scope.row.roleType === "1"
                ? "教练/交付小组组长"
                : scope.row.roleType === "2"
                ? "教练/学管师"
                : ""
            }}
          </span>
        </template> </el-table-column
      ><el-table-column v-if="tableType == '0'" label="状态" align="center" prop="isUse">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.c_is_use" :value="scope.row.isUse" />
        </template>
      </el-table-column>
      <el-table-column
        v-if="tableType == '0'"
        label="所学教段"
        align="center"
        prop="teachSection"
      >
        <template slot-scope="scope">
          {{
            scope.row.teachSection === "0"
              ? "小学"
              : scope.row.teachSection === "1"
              ? "初中"
              : scope.row.teachSection === "2"
              ? "高中"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="tableType == '0'"
        label="所学专业"
        align="center"
        prop="specialty"
      />
      <el-table-column
        v-if="tableType == '0'"
        label="课程分类"
        align="center"
        prop="classTypeName"
      />
      <el-table-column
        v-if="tableType == '0'"
        label="代课学员"
        align="center"
        prop="agentCourse"
      />
      <el-table-column
        v-if="tableType == '0'"
        label="上课学员"
        align="center"
        prop="formalCourse"
      />
      <el-table-column
        v-if="tableType == '0'"
        label="毕业院校"
        align="center"
        prop="graduate"
      />
      <el-table-column
        v-if="tableType == '0'"
        label="授课方式"
        align="center"
        prop="teachMethod"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.c_teach_method" :value="scope.row.teachMethod" />
        </template>
      </el-table-column>
      <el-table-column
        v-if="tableType == '0'"
        label="岗位类型"
        align="center"
        prop="position"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.c_position" :value="scope.row.position" />
        </template>
      </el-table-column>
      <el-table-column
        v-if="tableType == '0'"
        label="是否能试课"
        align="center"
        prop="isTestClass"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.course_yes_no" :value="scope.row.isTestClass" />
        </template>
      </el-table-column>
      <el-table-column
        v-if="tableType == '0'"
        label="学管师名称"
        align="center"
        prop="learnName"
      />
      <el-table-column
        v-if="tableType == '0'"
        label="交付小组名称"
        align="center"
        prop="payGroupName"
      />
      <el-table-column
        v-if="tableType == '1'"
        label="是否绑定交付小组"
        align="center"
        prop="isPayGroup"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.course_yes_no" :value="scope.row.isPayGroup" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 交付小组组长列表 -->

    <!-- 学管师列表 -->

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教练对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="125px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="企微账号" prop="wxUserId">
          <el-input v-model="form.wxUserId" placeholder="请输入企微账号" />
        </el-form-item>
        <el-form-item v-if="tableType != '2'" label="性格特点" prop="personality">
          <el-input v-model="form.personality" placeholder="请输入性格特点" />
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="所学专业" prop="specialty">
          <el-input v-model="form.specialty" placeholder="请输入所学专业" />
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="授课方式" prop="teachMethod">
          <el-radio-group v-model="form.teachMethod">
            <el-radio
              v-for="dict in dict.type.c_teach_method"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="毕业院校" prop="graduate">
          <el-input v-model="form.graduate" placeholder="请输入毕业院校" />
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="岗位类型" prop="position">
          <el-radio-group v-model="form.position">
            <el-radio
              v-for="dict in dict.type.c_position"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="是否能试课" prop="isTestClass">
          <el-radio-group v-model="form.isTestClass">
            <el-radio
              v-for="dict in dict.type.course_yes_no"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="学管师" prop="learnId">
          <el-select
            v-model="form.learnId"
            placeholder="请选择学管师"
            filterable
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in learns"
              value-key="id"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="交付小组" prop="payGroupId">
          <el-select
            v-model="form.payGroupId"
            placeholder="请选择交付小组"
            filterable
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in payGroups"
              value-key="id"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="课程分类" prop="classTypeId">
          <el-select
            v-model="form.classTypeId"
            placeholder="请选择课程分类"
            filterable
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in classTypes"
              value-key="id"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="所属学段" prop="teachSection">
          <el-select
            v-model="form.teachSection"
            placeholder="请选择所属学段"
            filterable
            size="large"
          >
            <el-option :key="0" label="小学" value="0" />
            <el-option :key="1" label="初中" value="1" />
            <el-option :key="2" label="高中" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="tableType == '0'" label="状态" prop="isUse">
          <el-radio-group v-model="form.isUse">
            <el-radio
              v-for="dict in dict.type.c_is_use"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item-->
<!--          v-if="tableType == '0'"-->
<!--          v-for="(domain, index) in coachTimeForm.coachTimes"-->
<!--          :key="domain.key"-->
<!--          label="时间"-->
<!--        >-->
<!--          &lt;!&ndash; <el-input v-model="domain.value" /> &ndash;&gt;-->
<!--          <el-select-->
<!--            v-model="domain.week"-->
<!--            placeholder="请选择时间"-->
<!--            size="large"-->
<!--            style="width: 170px"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in weeks"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value"-->
<!--            />-->
<!--          </el-select>-->
<!--          <el-time-picker-->
<!--            v-model="domain.startTime"-->
<!--            placeholder="开始时间"-->
<!--            style="width: 170px; margin: 8px"-->
<!--          />-->
<!--          <el-time-picker-->
<!--            v-model="domain.endTime"-->
<!--            placeholder="结束时间"-->
<!--            style="width: 170px; margin: 8px"-->
<!--          />-->
<!--          <el-button type="primary" @click="addDomain" style="margin-left: 10px" round-->
<!--            >增添</el-button-->
<!--          >-->
<!--          <el-button v-if="index != 0" type="danger" @click.prevent="removeDomain(domain)"-->
<!--            >-</el-button-->
<!--          >-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCoach,
  allCoach,
  getCoach,
  delCoach,
  addCoach,
  updateCoach,
} from "@/api/course/Coach";
import { listType } from "@/api/business/kctype";
import { delCoachTime } from "@/api/course/CoachTime";
import { listPayGroup, allPayGroups } from "@/api/course/PayGroup";
import { options } from "runjs";
export default {
  name: "Coach",
  dicts: ["course_yes_no", "c_is_use", "c_position", "sys_user_sex", "c_teach_method"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教练表格数据
      CoachList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 列表类型：0- 教练列表 1- 交付小组组长列表 2- 学管师列表
      tableType: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        sex: null,
        position: null,
        payGroupName: null,
        classTypeName: null,
        teachSection: null,
        roleType: "", // 默认查询教练列表
      },
      // 查询参数
      queryParams1: {
        pageNum: 1,
        pageSize: 9999,
        name: null,
        image: null,
        orderNum: null,
      },
      // 表单参数
      form: {},
      payGroups: [],
      learns: [],
      // 课程分类数据
      classTypes: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
        ],

      },
      coachTimeForm: {
        coachTimes: [
          {
            key: 1,
            week: "",
            startTime: "",
            endTime: "",
          },
        ],
      },
      weeks: [
        { value: "星期一", label: "星期一" },
        { value: "星期二", label: "星期二" },
        { value: "星期三", label: "星期三" },
        { value: "星期四", label: "星期四" },
        { value: "星期五", label: "星期五" },
        { value: "星期六", label: "星期六" },
        { value: "星期日", label: "星期日" },
      ],
    };
  },
  created() {
    this.refTable('0');
    // this.getList();
  },
  methods: {
    /** 查询教练列表 */
    getList() {
      this.loading = true;
      this.queryParams.roleType = this.tableType;
      listCoach(this.queryParams).then((response) => {
        this.CoachList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.refRules("0");
      });
      listType(this.queryParams1).then((response) => {
        this.classTypes = response.rows;
        console.log("[ classTypes ] >", this.classTypes);
      });
      allCoach({ roleType: "2" }).then((response) => {
        this.learns = response.data;
        console.log("[ response ] >", response);
      });
      listPayGroup(this.queryParams1).then((response) => {
        console.log("[ response ] >", response);
        this.payGroups = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    refRules(type) {
      // 修正roleType赋值逻辑，确保切换tab时roleType正确
      if (type === "0") {
        this.queryParams.roleType = null;
        this.rules = {
          name: [
            { required: true, message: "请输入姓名", trigger: "blur" },
            { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
          ],
          phone: [
            { required: true, message: "请输入联系方式", trigger: "blur" },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: "请输入正确的手机号码",
              trigger: "blur",
            },
          ],
          wxUserId: [
            { required: true, message: "请输企微账号", trigger: "blur" }
          ],
          learnId: [{ required: true, message: "请选择学管师", trigger: "change" }],
          classTypeId: [{ required: true, message: "请选择课程分类", trigger: "change" }],
          teachSection: [
            { required: true, message: "请选择所属学段", trigger: "change" },
          ],
        };
      } else {
        this.queryParams.roleType = type;
        this.rules = {
          name: [
            { required: true, message: "请输入姓名", trigger: "blur" },
            { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
          ],
          phone: [
            { required: true, message: "请输入联系方式", trigger: "blur" },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: "请输入正确的手机号码",
              trigger: "blur",
            },
          ],
        };
      }
    },
    // 刷新表格
    refTable(type) {
      this.refRules(type);
      this.tableType = type;
      this.form.roleType = type;
      console.log("[ qurey ] >", this.queryParams);
      console.log("[ roleType ] >", this.form);
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        roleId: null,
        roleType: this.tableType,
        name: null,
        phone: null,
        specialty: null,
        sex: null,
        personality: null,
        teachMethod: null,
        graduate: null,
        position: null,
        isTestClass: null,
        payGroupId: null,
        payGroupName: null,
        classTypeId: null,
        teachSection: null,
        isUse: null,
        createBy: null,
        createTime: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ids);
      this.names = selection.map((item) => item.name);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      if (this.tableType == "0") {
        this.title = "添加教练";
      } else if (this.tableType == "1") {
        this.title = "添加交付小组组长";
      } else if (this.tableType == "2") {
        this.title = "添加学管师";
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCoach(id).then((response) => {
        this.form = response.data;
        this.coachTimeForm.coachTimes = response.data.coachTimes;
        this.open = true;
        if (this.tableType == "0") {
          this.title = "修改教练";
        } else if (this.tableType == "1") {
          this.title = "修改交付小组组长";
        } else if (this.tableType == "2") {
          this.title = "修改学管师";
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.coachTimes = this.coachTimeForm.coachTimes;
      console.log("[ form ] >", this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCoach(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoach(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.name || this.names;
      this.$modal
        .confirm('是否确认删除"' + names + '"教练的数据项？')
        .then(function () {
          return delCoach(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "course/Coach/export",
        {
          ...this.queryParams,
        },
        `Coach_${new Date().getTime()}.xlsx`
      );
    },

    removeDomain(item) {
      const index = this.coachTimeForm.coachTimes.findIndex(
        (domain) => domain.key === item.key
      );
      console.log("[ index ] >", index);
      console.log("[ item ] >", item);
      if (index !== 0) {
        this.coachTimeForm.coachTimes.splice(index, 1);
      }
      if (item.id) {
        this.handleDeleteTime(item);
      }
    },
    addDomain() {
      this.coachTimeForm.coachTimes.push({
        key: new Date().getTime(),
        value: "",
      });
    },
    /** 删除按钮操作 */
    handleDeleteTime(row) {
      const ids = [];
      ids.push(row.id);
      return delCoachTime(ids).then(() => {
        this.$modal.msgSuccess("删除成功");
        getCoach(row.coachId).then((response) => {
          this.form = response.data;
          this.coachTimeForm.coachTimes = response.data.coachTimes;
          this.open = true;
          if (this.tableType == "0") {
            this.title = "修改教练";
          } else if (this.tableType == "1") {
            this.title = "修改交付小组组长";
          } else if (this.tableType == "2") {
            this.title = "修改学管师";
          }
        });
      });
    },
  },
};
</script>
<style>
.example-basic .el-date-editor {
  margin: 8px;
}
</style>
